package modbus_master_connector

import (
	"encoding/json"
	"errors"
	"go-iot-gateway/internal/channel"
	channel_define "go-iot-gateway/internal/channel/define"
	conf_table_define "go-iot-gateway/internal/conf_table/define"
	"go-iot-gateway/internal/logger"
	"strings"
)

func NewModbusMasterConnector(channelConfig conf_table_define.ChannelInfo,
	protocolConfInfos []*conf_table_define.ProtocolInfo) (channel_define.ConnectChannel, error) {

	connectParams := channel_define.ConnectParams{}
	err := json.Unmarshal([]byte(channelConfig.Chl_main_param), &connectParams)
	if err != nil {
		return nil, err
	}

	channelInfo := channel_define.ChannelInfo{}

	channelInfo.ChlId = channelConfig.Chl_id
	channelInfo.Name = channelConfig.Chl_name
	channelInfo.Addr = channelConfig.Chl_addr
	channelInfo.Desc = channelConfig.Chl_desc
	channelInfo.Protocol = strings.TrimSpace(channelConfig.Chl_protocol)
	channelInfo.SetStatus(channel_define.CONNECT_STATUS_CREATE, "已创建")
	channelInfo.ChannelType = channelConfig.Chl_type
	channelInfo.ProtocolType = channelConfig.Protocol_type
	channelInfo.Frequency = channelConfig.Chl_colt_freq
	channelInfo.WaitTime = channelConfig.Chl_wait_time
	channelInfo.ConnectParams = connectParams
	chlLogger := logger.NewChannelLogger(channelConfig.Chl_name)

	switch channelInfo.Protocol {
	case channel_define.MODBUS_RTU_MASTER:
		switch channelInfo.ProtocolType {
		//case 0: //tcp 协议
		//	chl := &ModbusTCPRTUConnector{}
		//	chl._connector = chl
		//	chl.channelManager = channel.Manager()
		//	chl.ChannelInfo = channelInfo
		//	chl.logger = chlLogger
		//	chl._init()
		//	return chl, nil
		default: //串口 协议
			chl := &ModbusRTUConnector{}
			chl._connector = chl
			chl.channelManager = channel.Manager()
			chl.ChannelInfo = channelInfo
			chl.logger = chlLogger
			chl._init(protocolConfInfos)
			return chl, nil
		}
	case channel_define.MODBUS_TCP_MASTER:
		chl := &ModbusTCPConnector{}
		chl._connector = chl
		chl.channelManager = channel.Manager()
		chl.ChannelInfo = channelInfo
		chl.logger = chlLogger
		chl._init(protocolConfInfos)
		return chl, nil
	}

	return nil, errors.New("通道类型不支持 " + channelInfo.Protocol)
}
